package com.svt;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FilenameFilter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.swing.*;
import javax.swing.filechooser.FileFilter;

import org.apache.commons.lang.StringUtils;

public class App{
	public static void main(String[] args) {
        JFrame frame = new JFrame("svt 视频处理工具");
        
        System.out.println(System.getProperties());
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); 
        
        frame.setSize(600, 300);
        frame.setLocation((screenSize.width-600)/2,(screenSize.height-300)/2);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        frame.add(panel);
        placeComponents(panel);
        frame.setVisible(true);
    }

    private static void placeComponents(final JPanel panel) {
        panel.setLayout(null);
        JLabel lb1 = new JLabel("片头视频:");
        lb1.setBounds(10,20,80,25);
        panel.add(lb1);

        final JTextField txt1 = new JTextField(100);
        txt1.setBounds(100,20,165,25);
        panel.add(txt1);
        
        JButton btn1 = new JButton("选择");
        btn1.setBounds(280, 20, 80, 25);
        panel.add(btn1);
        
        JLabel lb2 = new JLabel("目标文件或目录:");
        lb2.setBounds(10,60,80,25);
        panel.add(lb2);
        
        final JTextField txt2 = new JTextField(100);
        txt2.setBounds(100,60,165,25);
        panel.add(txt2);
        
        JButton btn2 = new JButton("选择");
        btn2.setBounds(280, 60, 80, 25);
        panel.add(btn2);
        
        JLabel lb3 = new JLabel("片尾视频:");
        lb3.setBounds(10,100,80,25);
        panel.add(lb3);
        
        final JTextField txt3 = new JTextField(100);
        txt3.setBounds(100,100,165,25);
        panel.add(txt3);
        
        JButton btn3 = new JButton("选择");
        btn3.setBounds(280, 100, 80, 25);
        panel.add(btn3);
        
        final JFileChooser fc1 = new JFileChooser();
        btn1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               int returnVal = fc1.showOpenDialog(panel);
               if (returnVal == JFileChooser.APPROVE_OPTION) {
                  java.io.File file = fc1.getSelectedFile();
                  txt1.setText(file.getAbsolutePath());
               }   
            }
         });
        
        final JFileChooser fc2 = new JFileChooser();
        fc2.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fc2.setFileFilter(new FileFilter() {
			public String getDescription() {
				return "videos";
			}

			@Override
			public boolean accept(File f) {
				return acceptFile(f);
			}
		});
        
        btn2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               int returnVal = fc2.showOpenDialog(panel);
               if (returnVal == JFileChooser.APPROVE_OPTION) {
                  java.io.File file = fc2.getSelectedFile();
                  txt2.setText(file.getAbsolutePath());
               }     
            }
         });
        
        final JFileChooser fc3 = new JFileChooser();
        btn3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               int returnVal = fc3.showOpenDialog(panel);
               if (returnVal == JFileChooser.APPROVE_OPTION) {
                  java.io.File file = fc3.getSelectedFile();
                  txt3.setText(file.getAbsolutePath());
               }   
            }
         });

        JButton btn = new JButton("开始");
        btn.setBounds(200, 220, 80, 25);
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            	String f1path = txt1.getText();
            	String f2path = txt2.getText();
            	String f3path = txt3.getText();
            	if(f1path==null||f1path.trim().length()==0||
            			f2path==null||f2path.trim().length()==0){
            		JOptionPane.showMessageDialog(null, "请选择正确的文件和目录", "error", JOptionPane.ERROR_MESSAGE);
            	}else{
            		File f1 = new File(f1path);     
                	File f2 = new File(f2path);
                	File f3 = (f3path==null||f3path.trim().length()==0)?null:new File(f3path);
                	File[] fs = null;
                	if(f2.isDirectory()){
                		File[] ls = f2.listFiles(new java.io.FileFilter() {
							public boolean accept(File pathname) {
								return acceptFile(pathname);
							}
						});
                		for (File file : ls) {
                			if(file.isFile()){
//                				fs = new File[]{f1,file,f3};
                				List<File> fl = new ArrayList<File>();
                        		fl.add(f1);
                        		fl.addAll(Arrays.asList(getFilePart(file)));
                        		fl.add(f3);
                        		fs = new File[fl.size()];
                        		fl.toArray(fs);
                        		System.out.println("处理文件："+file.getAbsolutePath());
                				VideoUtils.catVideo(fs, f2.getAbsolutePath(),getFileNameWithoutIdx(file.getName()));
                			}	
						}
                	}else{
                		List<File> fl = new ArrayList<File>();
                		fl.add(f1);
                		fl.addAll(Arrays.asList(getFilePart(f2)));
                		fl.add(f3);
                		fs = new File[fl.size()];
                		fl.toArray(fs);
                		System.out.println("处理文件："+f2.getAbsolutePath());
                		VideoUtils.catVideo(fs, f2.getParentFile().getAbsolutePath(),getFileNameWithoutIdx(f2.getName()));
                	}
            	}
            	JOptionPane.showMessageDialog(null, "处理完成", "success!", JOptionPane.INFORMATION_MESSAGE);
            }
         });
        panel.add(btn);
    }
    
    private static File[] getFilePart(File f){
    	String fname = StringUtils.substringBeforeLast(f.getName(), ".");
		final Pattern p =  Pattern.compile(".+_\\d+$");
		Matcher m = p.matcher(fname);
		if(m.matches()){
			final String sname = StringUtils.substringBeforeLast(fname,"_");
			File folder = f.getParentFile();
			String[] l = folder.list(new FilenameFilter() {
				public boolean accept(File dir, String name) {
					if(name.startsWith(sname)){
						String itemName =  StringUtils.substringBeforeLast(name, ".");
						String end = itemName.replaceFirst(sname, "");
						Pattern ptail = Pattern.compile("^_\\d+");
						boolean ok = ptail.matcher(end).matches();
						return ok;
					}
					return false;
				}
			});
			Arrays.sort(l, new Comparator<String>() {
				public int compare(String o1, String o2) {
					String idx1 = StringUtils.substringAfterLast(StringUtils.substringBeforeLast(o1, "."),"_");
					String idx2 = StringUtils.substringAfterLast(StringUtils.substringBeforeLast(o2, "."),"_");
					return Integer.parseInt(idx1)-Integer.parseInt(idx2);
				}
			});
			String folderPath = folder.getAbsolutePath().replaceAll("\\\\", "/");
			if(!folderPath.endsWith("/")){
				folderPath += "/";
			}
			File[] fs = new File[l.length];
			for (int i=0;i<l.length;i++) {
				fs[i] = new File(folderPath+l[i]);
			}
			return fs;
		}else{
			return new File[]{f};
		}
    }
    
    private static String getFileNameWithoutIdx(String filename){
    	String postfix = "."+StringUtils.substringAfterLast(filename, ".");
    	String sname = StringUtils.substringBeforeLast(filename, ".");
		final Pattern p =  Pattern.compile("^(.+)_\\d+$");
		Matcher m = p.matcher(sname);
		if(m.find()){
			sname = m.group(1);
		}
		return sname+postfix;
    }
    
    public static boolean acceptFile(File f) {
		if(f.isDirectory()) return true;
		String filename = f.getName().toLowerCase();
		Pattern p = Pattern.compile(".+\\.(mp4|avi|.rmvb|.rm|.flv|.mpg|.mkv)");
		Matcher m = p.matcher(filename);
		// 是否完全匹配
		boolean isvideo = m.matches();
		
		if(isvideo){
			String name = StringUtils.substringBeforeLast(filename, ".");
			p =  Pattern.compile(".+_\\d+$");
			m = p.matcher(name);
			if(m.matches()){
				String idx = StringUtils.substringAfterLast(name, "_");
				if("1".equals(idx)){
					return true;
				}else{
					return false;
				}
			}else{
				return true;
			}
		}else{
			return false;
		}
	}
}
